package cl.DAOs;

import org.hibernate.*;
import cl.POJOs.*;
import cl.DAOs.HibernateUtil;
import java.util.List;
import org.hibernate.criterion.Order;

public class TutorDao {

    private Session session;
    private Transaction trans;

    private List<Tutor> lstTutors;

    public void Registrar(Tutor tut) throws Exception {
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            trans = session.beginTransaction();
            session.save(tut);
            trans.commit();

        } catch (Exception ex) {
            trans.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

    public void Modificar(Tutor tut) throws Exception {
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            trans = session.beginTransaction();
            session.update(tut);
        } catch (Exception ex) {
            trans.rollback();
            throw ex;
        } finally {
            session.close();
        }
    }

    public List<Tutor> Listar() throws Exception {
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            Criteria cri = session.createCriteria(Tutor.class);
            cri.addOrder(Order.asc("apellido"));
            lstTutors = cri.list();
        } catch (Exception ex) {
            throw ex;

        }
        session.close();
        return lstTutors;
    }

    public Tutor verificarDatos(Tutor tutor) throws Exception {
        Tutor tut = null;

        try {
            session = HibernateUtil.getSessionFactory().openSession();
            String consulta = "From Tutor Where rut= '" + tutor.getRut()
                    + "' and clave ='" + tutor.getClave() + "'";
            Query query = session.createQuery(consulta);
            if (!query.list().isEmpty()) {
                tut = (Tutor) query.list().get(0);
            }
        } catch (Exception e) {
            throw e;
        }
        session.close();
        return tut;

    }

    public int Eliminar(Tutor tut) throws Exception {
        int a = 1;
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            trans = session.beginTransaction();
            session.delete(tut);
            trans.commit();

        } catch (Exception ex) {
            trans.rollback();
            a=0;
            
            
        } finally {
            session.close();
        }
        return a;
    }

}
